﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security;
using System.Security.Cryptography;
using System.Web.Security;
using System.Web.UI.WebControls;

namespace SecurityAgentServiceWebControls
{
    public class SASAspNetLoginControl : System.Web.UI.WebControls.Login
    {
        protected override void OnAuthenticate(AuthenticateEventArgs e)
        {
            // Validate the user
            bool Authenticated = false;

            Authenticated = AuthenticateUser(UserName, Password);

            e.Authenticated = Authenticated;


        }

        protected bool AuthenticateUser(string userName, string password)
        {
            HttpContext context = HttpContext.Current;
            if (context == null)
            {
                throw new InvalidOperationException("Http context cannot be null.");
            }

            MembershipProvider provider = Membership.Provider;

            if (provider == null)
            {
                throw new InvalidOperationException("MembershipProvider cannot be null.");
            }

            provider = provider as SecurityAgent.SecurityAgentMembershipProvider;

            if (provider == null)
            {
                throw new InvalidOperationException("The specified MembershipProvider must be of type DynamicApplicationsSqlMembershipProvider.");
            }


            //System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding();
            //byte[] uePassword = ue.GetBytes(password);
            //byte[] RetVal = null;

            //switch (provider.PasswordFormat)
            //{
            //    case MembershipPasswordFormat.Clear:
            //        RetVal = uePassword;
            //        break;
            //    case MembershipPasswordFormat.Hashed:
            //         HMACSHA1 SHA1KeyedHasher = new HMACSHA1();
            //         SHA1KeyedHasher.Key = ue.GetBytes(((SecurityAgent.SecurityAgentMembershipProvider)provider).ApplicationKey);
            //         RetVal = SHA1KeyedHasher.ComputeHash(uePassword);
            //        break;
            //    default:
            //        throw new Exception("Unsupport Password Format");
                    
            //}

            //string newPass = ue.GetString(RetVal);

            string userToken = ((SecurityAgent.SecurityAgentMembershipProvider)provider).ValidateAndRegisterUser(userName, password);
            
            if( !String.IsNullOrEmpty(userToken))
            {
                ////HttpCookie cookie = FormsAuthenticationHelper.StoreUserDataInAuthenticationCookie(userName, "SASTK=" + userToken, true);
                //FormsAuthentication.Initialize();

                ////The AddMinutes determines how long the user will be logged in after leaving
                ////the site if he doesn't log off.
                //FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1,
                //    userName, DateTime.Now,
                //    DateTime.Now.AddMinutes(30), false, "SASTK=" + userToken,
                //    FormsAuthentication.FormsCookiePath);
                //Page.Response.Cookies.Add(cookie);
                //Page.Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, false));

                FormsAuthentication.Initialize();

                //The AddMinutes determines how long the user will be logged in after leaving
                //the site if he doesn't log off.
                FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1,
                    userName, DateTime.Now,
                    DateTime.Now.AddMinutes(30), false, "SASTK=" + userToken,
                    FormsAuthentication.FormsCookiePath);
                Page.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName,
                    FormsAuthentication.Encrypt(fat)));
                Page.Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, false));

                return true;
            }
            else
                return false;
        }

    }
}
